#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

class ShellCommandExecutor : public rclcpp::Node
{
public:
    ShellCommandExecutor() : Node("topic_to_shell")
    {
        subscription_ = this->create_subscription<std_msgs::msg::String>(
            "shell_command", 10, std::bind(&ShellCommandExecutor::listener_callback, this, std::placeholders::_1));
    }

private:
    void listener_callback(const std_msgs::msg::String::SharedPtr msg)
    {
        RCLCPP_INFO(this->get_logger(), "Received command: '%s'", msg->data.c_str());
        int status = std::system(msg->data.c_str());
        if (status == -1) {
            RCLCPP_ERROR(this->get_logger(), "Failed to execute command");
        } else {
            RCLCPP_INFO(this->get_logger(), "Command executed with status code %d", WEXITSTATUS(status));
        }
    }

    rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char** argv)
{
    rclcpp::init(argc, argv);
    auto node = std::make_shared<ShellCommandExecutor>();
    rclcpp::spin(node);
    // node->destroy_node();
    rclcpp::shutdown();
    return 0;
}